/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.core.util;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.ConversionService;
import org.springframework.util.Assert;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Field accessor wrapper implementation.
 *
 * @author Xiaohai Zhang
 * @since 2013-08-19 09:50
 */
@Slf4j
public class FieldAccessor {
    protected final ConversionService conversionService = ConversionUtils.getConversionService();

    @Getter private final Class<?> clazz;
    @Getter private final Field field;
    @Getter private final String fieldName;
    @Getter private final Class<?> fieldType;
    @Getter(AccessLevel.PROTECTED) private final Method getter;
    @Getter(AccessLevel.PROTECTED) private final Method setter;

    public FieldAccessor(Class<?> clazz, Field field) {
        Assert.notNull(clazz);
        Assert.notNull(field);

        this.clazz = clazz;
        this.field = field;
        this.fieldName = field.getName();
        this.fieldType = field.getType();
        this.getter = initializeGetter();
        this.setter = initializeSetter();
    }

    public Object get(Object obj) {
        Assert.notNull(obj);
        try {
            if (getter != null) {
                return getter.invoke(obj);
            }
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            return field.get(obj);
        } catch (IllegalAccessException | InvocationTargetException ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        }
    }

    public void set(Object obj, Object value) {
        Assert.notNull(obj);
        if (value != null && !fieldType.isAssignableFrom(value.getClass())) {
            Assert.isTrue(conversionService.canConvert(value.getClass(), fieldType));
            value = conversionService.convert(value, fieldType);
        }
        try {
            if (setter != null) {
                setter.invoke(obj, value);
                return;
            }
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            field.set(obj, value);
        } catch (IllegalAccessException | InvocationTargetException ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        }
    }

    // Private methods:

    private Method initializeGetter() {
        Method getter = null;
        String prefix = fieldType == boolean.class ? "is" : "get";
        String getterMethodName = prefix + StringUtils.capitalize(fieldName);
        try {
            getter = clazz.getDeclaredMethod(getterMethodName);
            if (!getter.getReturnType().isAssignableFrom(fieldType)) {
                FieldAccessor.log.warn("Getter method '{}.{}' has incompatible return type", clazz.getName(), getterMethodName);
                getter = null;
            }
        } catch (NoSuchMethodException ignored) {
            // no getter method found, ignored
        }
        if (getter != null && !getter.isAccessible()) {
            getter.setAccessible(true);
        }
        return getter;
    }

    private Method initializeSetter() {
        Method setter = null;
        String setterMethodName = "set" + StringUtils.capitalize(fieldName);
        try {
            setter = clazz.getDeclaredMethod(setterMethodName, fieldType);
            if (setter.getReturnType() != void.class) {
                FieldAccessor.log.warn("Setter method '{}.{}' must have no return type", clazz.getName(), setterMethodName);
                setter = null;
            }
        } catch (NoSuchMethodException ignored) {
            // no setter method found, ignored
        }
        if (setter != null && !setter.isAccessible()) {
            setter.setAccessible(true);
        }
        return setter;
    }
}
